// index.js

import {
  startFastOta,
  startOta
} from "../../ota/bx_ota.js"


Page({
  data: {
    fastMode: true,
    currentIndex: 0,
    updating: false,
    errorMessage: null,
    debug: false,
    deviceId: null,
    otaTasks: [], //[{selectedFile,address,rawData,desc,progress},{}..]
  },

  onReady() {
    var that = this
    wx.getSystemInfo({
      success: (e) => {
        that.setData({
          debug: e.enableDebug
        })
      }
    })
  },
  onDebugChanged() {
    let newValue = !this.data.debug
    wx.setEnableDebug({
      enableDebug: newValue,
    })
  },
  onModeSwitchChange: function (e) {
    this.setData({
      fastMode: e.detail.value
    })
  },
  onFindDeviceTap: function (e) {
    this.setData({
      currentIndex: 0
    })
    wx.navigateTo({
      url: '../scan/scan'
    })
  },
  onSelectFileTap: function (e) {
    this.setData({
      currentIndex: 1
    })
    wx.navigateTo({
      url: '../task/task'
    })

  },
  onFileSelected(file, address) {
    let that = this
    let otaTasks = this.data.otaTasks
    readFileToArrayBuffer(file).then(
      (res) => {
        console.log(res)
        otaTasks.push({
          selectedFile: file,
          address: address,
          rawData: res
        })
        that.setData({
          otaTasks: otaTasks
        })
        that.applyCurrentIndex()
      },
      (err) => {
        console.error(err)
      }
    )
  },
  onDeviceSelected(deviceId) {
    this.setData({
      deviceId: deviceId
    })
    this.applyCurrentIndex()
  },
  onTaskRemove(e) {
    let index = e.currentTarget.dataset.index
    this.data.otaTasks.splice(index, 1)
    let newTasks = this.data.otaTasks
    this.setData({
      otaTasks: newTasks
    })
    if (newTasks.length == 0) {
      this.applyCurrentIndex()
    }
  },
  onStartTap(e) {
    let that = this
    this.setData({
      updating: true,
      currentIndex: 2
    })
    wx.setKeepScreenOn({
      keepScreenOn: true,
    })
    let onStateChanged = function (state) {
      let index = state.index
      let otaTasks = that.data.otaTasks
      if (index >= 0 && index < otaTasks.length) {
        let otaTask = otaTasks[index]
        otaTask.progress = Math.floor(state.progress * 100)
        console.log(state)
        if (state.startTime > 0) {
          if (state.endTime == 0) {
            otaTask.desc = "更新中..."
          } else {
            if (state.errorMessage == null || state.errorMessage == "") {
              otaTask.desc = `成功(${(state.endTime - state.startTime) / 1000}秒)`
            } else {
              otaTask.desc = "失败：" + state.errorMessage
            }
          }
        }
        that.setData({
          otaTasks: otaTasks,
        })
      }
    }
    let onFinish = function (res) {
      console.log(res)
      that.setData({
        updating: false
      })
      wx.setKeepScreenOn({
        keepScreenOn: false,
      })
    }
    if (that.data.deviceId && that.data.otaTasks.length > 0) {
      if (that.data.fastMode) {
        startFastOta(that.data.deviceId, that.data.otaTasks, onStateChanged, onFinish)
      } else {
        startOta(that.data.deviceId, that.data.otaTasks[0], onStateChanged, onFinish)
      }
    }

  },
  applyCurrentIndex() {
    var index = 0
    if (this.data.deviceId && this.data.otaTasks.length > 0) {
      index = 2
    } else if (this.data.deviceId && this.data.otaTasks.length == 0) {
      index = 0
    } else if (this.data.deviceId == null && this.data.otaTasks.length > 0) {
      index = 1
    } else {
      0
    }
    let that = this
    setTimeout(() => {
      that.setData({
        currentIndex: index
      })
    }, 300)
  },
  onRecoveryPage(){
    wx.navigateTo({
      url: '../recovery/recovery'
    })
  }
})

/**
 * 根据文件转字节数组
 * @param {*} file 
 */
function readFileToArrayBuffer( /*wxfile*/ file) {
  return new Promise((resolve, reject) => {
    if (file == null) reject("File cant be null")
    const fs = wx.getFileSystemManager()
    const ab = new ArrayBuffer(file.size)
    fs.open({
      filePath: file.path,
      flag: 'r',
      success(res) {
        fs.read({
          fd: res.fd,
          arrayBuffer: ab,
          length: file.size,
          success(res) {
            resolve(ab)
          },
          fail(err) {
            reject(err)
          }
        })
      },
      fail(err) {
        reject(err)
      }
    })
  })
}